package com.southminority.ethnic.controller.heritage;

import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.service.heritage.HeritageService;
import com.southminority.ethnic.controller.heritage.vo.HeritageVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 非遗项目展示控制器
 * 提供前端展示用的REST API
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "06 - 非物质文化遗产展示API", description = "【前台】非物质文化遗产模块查询与展示相关接口")
@RestController
@RequestMapping("/api/heritage")
@CrossOrigin
public class HeritageController {

    private final HeritageService heritageService;

    public HeritageController(HeritageService heritageService) {
        this.heritageService = heritageService;
    }

    /**
     * 获取所有非遗项目列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取所有已发布的非遗项目列表", description = "用于前端首页或列表页，默认按浏览量和创建时间降序排序。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功",
                    content = @Content(mediaType = "application/json",
                            schema = @Schema(implementation = R.class))),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<List<HeritageVO>> getHeritageList() {
        try {
            List<HeritageVO> heritageList = heritageService.getHeritageList();
            return R.ok(heritageList);
        } catch (Exception e) {
            log.error("获取非遗项目列表失败", e);
            return R.fail("获取非遗项目列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据条件筛选非遗项目列表
     */
    @GetMapping("/search")
    @Operation(summary = "根据条件动态筛选和排序非遗项目列表", description = "提供多种参数进行组合查询，支持分页和排序。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "查询失败")
    })
    public R<List<HeritageVO>> searchHeritageList(
            @Parameter(description = "非遗类型", example = "民间文学") @RequestParam(required = false) String heritageType,
            @Parameter(description = "级别", example = "国家级") @RequestParam(required = false) String level,
            @Parameter(description = "所属地区", example = "贵州省") @RequestParam(required = false) String region,
            @Parameter(description = "所属民族", example = "苗族") @RequestParam(required = false) String ethnicGroup,
            @Parameter(description = "搜索关键词，将模糊匹配名称、简介和关键词字段", example = "古歌") @RequestParam(required = false) String keyword,
            @Parameter(description = "排序字段", example = "view_count", schema = @Schema(allowableValues = {"view_count", "create_time"})) @RequestParam(required = false, defaultValue = "view_count") String sortBy,
            @Parameter(description = "排序顺序", example = "desc", schema = @Schema(allowableValues = {"asc", "desc"})) @RequestParam(required = false, defaultValue = "desc") String sortOrder) {
        try {
            List<HeritageVO> heritageList = heritageService.getHeritageListByCondition(
                heritageType, level, region, ethnicGroup, keyword, sortBy, sortOrder);
            return R.ok(heritageList);
        } catch (Exception e) {
            log.error("筛选非遗项目列表失败", e);
            return R.fail("筛选非遗项目列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取非遗项目详情
     */
    @GetMapping("/detail/{id}")
    @Operation(summary = "获取单个非遗项目的详细信息", description = "根据项目ID查询，返回包含传承人、关联研究等完整信息的对象。注意：此接口**不会**自动增加浏览次数。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "非遗项目不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<HeritageVO> getHeritageDetail(@Parameter(description = "非遗项目的唯一ID", example = "1", required = true) @PathVariable Long id) {
        try {
            HeritageVO heritageVO = heritageService.getHeritageDetail(id);
            return R.ok(heritageVO);
        } catch (Exception e) {
            log.error("获取非遗项目详情失败, ID: {}", id, e);
            return R.fail("获取非遗项目详情失败: " + e.getMessage());
        }
    }

    /**
     * 增加浏览次数
     */
    @PutMapping("/view/{id}")
    @Operation(summary = "为指定非遗项目增加一次浏览次数", description = "每次调用此接口，对应ID的非遗项目浏览次数（view_count）会加一。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "操作成功，返回更新后的总浏览次数"),
            @ApiResponse(responseCode = "404", description = "非遗项目不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Integer> increaseViewCount(@Parameter(description = "非遗项目的唯一ID", example = "1", required = true) @PathVariable Long id) {
        try {
            Integer viewCount = heritageService.increaseViewCount(id);
            return R.ok(viewCount);
        } catch (Exception e) {
            log.error("增加浏览次数失败, ID: {}", id, e);
            return R.fail("增加浏览次数失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有非遗类型列表
     */
    @GetMapping("/types")
    @Operation(summary = "获取所有不重复的非遗类型列表", description = "用于前端筛选菜单，返回一个包含所有非遗类型的字符串列表。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<List<String>> getHeritageTypes() {
        try {
            List<String> types = heritageService.getHeritageTypes();
            return R.ok(types);
        } catch (Exception e) {
            log.error("获取非遗类型列表失败", e);
            return R.fail("获取非遗类型列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有级别列表
     */
    @GetMapping("/levels")
    @Operation(summary = "获取所有不重复的项目级别列表", description = "用于前端筛选菜单，返回一个包含所有级别的字符串列表。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<List<String>> getLevels() {
        try {
            List<String> levels = heritageService.getLevels();
            return R.ok(levels);
        } catch (Exception e) {
            log.error("获取级别列表失败", e);
            return R.fail("获取级别列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有地区列表
     */
    @GetMapping("/regions")
    @Operation(summary = "获取所有不重复的地区列表", description = "用于前端筛选菜单，返回一个包含所有地区的字符串列表。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<List<String>> getRegions() {
        try {
            List<String> regions = heritageService.getRegions();
            return R.ok(regions);
        } catch (Exception e) {
            log.error("获取地区列表失败", e);
            return R.fail("获取地区列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有民族列表
     */
    @GetMapping("/ethnic-groups")
    @Operation(summary = "获取所有不重复的民族列表", description = "用于前端筛选菜单，返回一个包含所有民族的字符串列表。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<List<String>> getEthnicGroups() {
        try {
            List<String> ethnicGroups = heritageService.getEthnicGroups();
            return R.ok(ethnicGroups);
        } catch (Exception e) {
            log.error("获取民族列表失败", e);
            return R.fail("获取民族列表失败: " + e.getMessage());
        }
    }

    /**
     * 测试接口连通性
     */
    @GetMapping("/test")
    @Operation(summary = "测试接口连通性", description = "一个简单的GET请求，用于检查服务是否正常运行。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "服务正常")
    })
    public R<String> test() {
        return R.ok("非遗项目展示服务正常运行");
    }
} 